import os

# Set up directories
currpath = os.path.dirname(os.path.abspath(__file__))
def normjoin(path1, path2):
  return os.path.normpath(os.path.join(path1, path2)) + '/'
rppath = normjoin(currpath, '../parser/repoparsed/')
sppath = normjoin(currpath, '../parser/srcparsed/')
repopath = normjoin(currpath, '../sources/')
srcpath = normjoin(currpath, '../gosrc/')
parserpath = normjoin(currpath, '../parser/')

print 'Clearing old parsed files'
os.system('rm -rf '+rppath+'*')
os.system('rm -rf '+sppath+'*')

print 'Finding repo and gosrc .go files'
repofiles = os.popen("find "+repopath+" -name '*.go'").read().splitlines()
srcfiles = os.popen("find "+srcpath+" -name '*.go'").read().splitlines()
print str(len(repofiles)) + ' repo files and ' + str(len(srcfiles)) + ' gosrc files'

def parsefiles(filelist, outdir):
  name_index = 0
  for f in filelist:
    if os.path.isdir(f):
      continue
    name_index += 1
    cmd = parserpath + '8.out ' + f + ' > ' + outdir + str(name_index) + '.parsed'
    status = os.system(cmd)
    if status != 0:
      print '\tfailed parsing '+ f
      os.system('rm ' + outdir + str(name_index) + '.parsed')
      name_index -= 1

print 'Parsing repo files'
parsefiles(repofiles, rppath)
print 'Parsing gosrc files'
parsefiles(srcfiles, sppath)

print 'Done'
